<template>
  <a-modal :width="1200" v-model:visible="showHandleWarehousing" title="提交入库单" ok-text="生成入库单" top="8vh" title-align="start" :on-before-ok="submitData" :ok-loading="submitLoading" :mask-closable="false" @cancel="closedDialog">
    <div class="order-w flex">
      <div class="order-detail-item" style="width: 300px">
        <p>
          <span class="label">交货单号：</span>
          <span class="highlight">{{ currentItem.billNo }}</span>
        </p>
        <p>
          <span class="label">目的仓库：</span>
          <span>{{ currentItem.warehouseName }}({{ currentItem.warehouseCode }})</span>
        </p>
      </div>
      <div class="order-detail-item" style="width: 300px">
        <p><span class="label">供应商：</span>{{ currentItem.supplierName }}({{ currentItem.supplierCode }})</p>
        <p><span class="label">交货日期：</span>{{ $setTime(currentItem.gmtDelivery, 'YYYY/MM/DD HH:mm') }}</p>
      </div>
      <div class="order-detail-item" style="width: 300px">
        <p><span class="label">签收人：</span>{{ currentItem.signUname }}</p>
        <p><span class="label">签收时间：</span>{{ $setTime(currentItem.gmtSign, 'YYYY/MM/DD HH:mm') }}</p>
      </div>
    </div>
    <a-table
      class="table-two-line show-border-table"
      ref="tableRef"
      row-key="id"
      :data="purchaseOrders"
      :scroll="{
        y: 'calc(84vh - 240px)',
      }"
      :span-method="spanMethodAll"
      size="mini"
      :bordered="{ cell: true }"
      :pagination="false"
    >
      <template #columns>
        <a-table-column title="采购单" :width="100">
          <template #cell="{ record }">
            <p class="highlight">{{ record.purchaseNo }}</p>
          </template>
        </a-table-column>
        <a-table-column data-index="img" title="图片" :width="60">
          <template #cell="{ record }">
            <ImgPopover :src="record.productImg">
              <template #con>
                <a-image width="40" height="40" fit="contain" :src="record.productImg" />
              </template>
            </ImgPopover>
          </template>
        </a-table-column>
        <a-table-column title="产品名称">
          <template #cell="{ record }">
            <TextLimit :val="record.productName" />
          </template>
        </a-table-column>
        <a-table-column data-index="sku" title="SKU/类目" :width="140">
          <template #cell="{ record }">
            <ShowSpuDetailBySku :val="record.sku" :showLimit="true" :rows="1" />
            <p>{{ record.cateName || '--' }}</p>
          </template>
        </a-table-column>
        <a-table-column data-index="productSpecs" title="SKU规格" :width="100">
          <template #cell="{ record }">
            <TextLimit :val="getProductSpecs(record)" />
          </template>
        </a-table-column>
        <a-table-column data-index="deliveryRealAmt" title="实际交货数" :width="80" />
        <a-table-column data-index="deliveryRealAmt" title="待入库数" :width="80" />
        <a-table-column title="入库明细">
          <a-table-column data-index="shop" title="店铺" :width="140" cell-class="shopInfo">
            <template #cell="{ record }">
              <div class="shop-list" v-for="(item, i) in record.planItems" :key="i">
                <div class="item" style="width: 140px">
                  {{ item.shopName }}
                </div>
                <div class="item" style="width: 70px">
                  {{ item.salesmanName }}
                </div>
                <div class="item" style="width: 140px">
                  <TextLimit :val="item.msku || '--'" :rows="2" style="width: 130px" />
                </div>
                <div class="item" style="width: 70px">
                  <p>{{ item.purchaseAmt }}</p>
                </div>
                <div class="item" style="width: 100px">
                  <a-input-number :min="1" v-model="item.num" style="width: 70px" placeholder="" />
                </div>
              </div>
            </template>
          </a-table-column>
          <a-table-column title="货主" :width="70" />
          <a-table-column title="MSKU" :width="140" />
          <a-table-column title="采购数量" :width="70" />
          <a-table-column :width="100">
            <template #title>
              <p>
                <span class="warningColor">*</span>
                <span>入库数</span>
              </p>
            </template>
          </a-table-column>
        </a-table-column>
      </template>
    </a-table>
  </a-modal>
</template>
<script lang="ts" setup>
  import { ref, onMounted } from 'vue'
  import { Message } from '@arco-design/web-vue'
  import { submitDeliveryReceipt, getDeliveryInfo } from '@/api/purchase'
  import { parseJson } from '@/utils'

  onMounted(async () => {
    setDefaultData()
  })
  const emit = defineEmits(['closed', 'success'])
  const props = defineProps({
    isShow: {
      type: Boolean,
      default: false,
    },
    currentItem: {
      type: Object,
      default: () => {},
    },
  })

  const showHandleWarehousing = ref(props.isShow)
  const purchaseOrders = ref<Array<any>>([])
  const submitLoading = ref(false)

  // 添加初始化数据
  async function setDefaultData() {
    const res: any = await getDeliveryInfo({ id: props.currentItem.id })
    let detail = res?.data || {}
    purchaseOrders.value =
      detail.billItems?.map((el: any) => {
        let obj = JSON.parse(JSON.stringify(el))
        obj.planItems?.forEach((item: any) => {
          item.num = 0
        })
        return obj
      }) || []
  }
  // 关闭
  function closedDialog() {
    showHandleWarehousing.value = false
    emit('closed')
  }
  // 合并单元格
  function spanMethodAll(option: any) {
    let { column } = option
    if (column.dataIndex === 'shop') {
      return { rowspan: 1, colspan: 5 }
    }
  }
  // 判断空
  function isNull(val: any) {
    return val === undefined || val === null || val === ''
  }
  // 显示sku规格
  function getProductSpecs(item: any) {
    let productSpecs = item.productSpecs ? parseJson(item.productSpecs, []) : []
    return productSpecs.map((el: any) => el.valueCn)?.join('*') || '--'
  }
  // 保存
  async function submitData() {
    let flag = false
    let deliveryItems: Array<any> = []
    purchaseOrders.value.forEach((el: any) => {
      el.planItems?.forEach((item: any) => {
        let obj = {
          id: item.id,
          purchaseItemId: item.purchaseItemId,
          deliveryItemId: el.id,
          shopId: el.shopId,
          warehouseAmt: item.num,
        }
        deliveryItems.push(obj)
        if (item.num > 0) flag = true
      })
    })
    if (!flag) {
      Message.error('最少添加一个入库数')
      return false
    }
    const res: any = await submitDeliveryReceipt({
      id: props.currentItem?.id,
      deliveryItems: deliveryItems,
    })
    if (!res) return false
    Message.success('提交入库单成功')
    emit('success')
    closedDialog()
  }
</script>
<style lang="less" scoped>
  .order-w {
    padding: 10px;
    background-color: var(--color-neutral-2);
    color: #666;
    margin-bottom: 10px;
    .order-detail-item {
      width: 200px;
    }
  }
  .edit-icon {
    font-size: 16px;
    margin-left: 5px;
    cursor: pointer;
  }
  :deep(td.shopInfo .arco-table-cell) {
    padding: 0 !important;
  }
  .shop-list {
    display: flex;
    border-bottom: 1px solid var(--color-neutral-3);
    &:last-child {
      border-bottom: none;
    }

    .item {
      height: 56px;
      display: flex;
      align-items: center;
      padding: 0 5px;
      border-right: 1px solid var(--color-neutral-3);
      &:last-child {
        border-right: none;
      }
    }
  }
</style>
